import { createRouter, createWebHashHistory } from "vue-router";
import { getToken } from "@/utils/auth";
import store from "@/store";

// 一次性导入多个模块
//      Vite      import.meta.glob()
//      Webpack   require.context()
const aaa = import.meta.glob([
  "../views/**/index.vue",
  "!../views/**/components",
  "!../views/login",
]);

// 将 aaa 中的 key 修改为 '/dashboard/conosle' 这种格式
const modules = {};
for (let key in aaa) {
  const newKey = key.replace("../views", "").replace("/index.vue", "");
  modules[newKey] = aaa[key];
}

// console.log("=== aaa", aaa);
// console.log("=== modules", modules);

// const modules = {
//   "/dashboard/console": () => import("@/views/dashboard/console/index.vue"),
//   "/dashboard/monitor": () => import("@/views/dashboard/monitor/index.vue"),
//   "/dashboard/workplace": () => import("@/views/dashboard/workplace/index.vue"),
//   "/system/menu": () => import("@/views/system/menu/index.vue"),
//   "/system/user": () => import("@/views/system/user/index.vue"),
//   "/system/role": () => import("@/views/system/role/index.vue"),
// };

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "index",
      component: () => import("@/layout/index.vue"),
      children: [
        {
          path: "",
          name: "home",
          component: () => import("@/views/home/index.vue"),
        },
        // {
        //   path: "/dashboard/console",
        //   name: "dashboard-console",
        //   component: () => import("@/views/dashboard/console/index.vue"),
        // },
        // {
        //   path: "/dashboard/monitor",
        //   name: "dashboard-monitor",
        //   component: () => import("@/views/dashboard/monitor/index.vue"),
        // },
        // {
        //   path: "/dashboard/workplace",
        //   name: "dashboard-workplace",
        //   component: () => import("@/views/dashboard/workplace/index.vue"),
        // },
        // {
        //   path: "/system/menu",
        //   name: "system-menu",
        //   component: () => import("@/views/system/menu/index.vue"),
        // },
        // {
        //   path: "/system/user",
        //   name: "system-user",
        //   component: () => import("@/views/system/user/index.vue"),
        // },
        // {
        //   path: "/system/role",
        //   name: "system-role",
        //   component: () => import("@/views/system/role/index.vue"),
        // },
        // {
        //   path: "/examples/tree",
        //   name: "examples-tree",
        //   component: () => import("@/views/examples/tree/index.vue"),
        // },
        // {
        //   path: "/examples/hello",
        //   name: "examples-hello",
        //   component: () => import("@/views/examples/hello/index.vue"),
        // },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/index.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("@/views/errors/404.vue"),
    },
  ],
});

// 白名单路由（不需要登录也可以访问的）
const whiteNames = ["login"];
router.beforeEach(async (to) => {
  // 获取token
  const token = getToken();

  // 不是白名单
  if (!whiteNames.includes(to.name)) {
    // 没有登录
    if (!token) {
      return { name: "login", query: { redirect: to.fullPath } };
    }

    // 没有用户信息
    if (!store.state.user.info) {
      // 派发获取用户信息的动作，获取拥有权限的菜单数据
      const authRoutes = await store.dispatch("user/getInfo");

      // console.log("=== authRoutes", authRoutes);
      // 动态添加路由
      authRoutes.forEach((item) => {
        router.addRoute("index", {
          path: item.router,
          name: item.router.split("/").join("-").substr(1),
          // import() 动态导入模块中，不推荐使用变量
          // component: () => import(`../views/${item.viewPath}.vue`),

          component: modules[item.router],
        });
      });
      // console.log("=== addRoute 完成 getRoutes", router.getRoutes());
      // 重新重定向一次
      return to.fullPath;
    }
  }
});

/**
 * 重置路由
 *    将动态添加的都给删除
 */
router.reset = () => {
  store.getters["user/authRoutes"].forEach((item) => {
    const name = item.router.split("/").join("-").substr(1);
    router.removeRoute(name);
  });

  // console.log("=== removeRoute 完成 getRoutes", router.getRoutes());
};

export default router;

// {
//   '/dashboard/conosle': () => import('../view/dashboard/console/index.vue'),
//   '/dashboard/1': () => import('../view/dashboard/1/index.vue'),
//   '/dashboard/2': () => import('../view/dashboard/2/index.vue'),
//   '/dashboard/3': () => import('../view/dashboard/3/index.vue'),
//   '/dashboard/4': () => import('../view/dashboard/4/index.vue'),
//   '/dashboard/5': () => import('../view/dashboard/5/index.vue'),
// }
